#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>

pthread_rwlock_t lock;

int data;

void* fun_rd(void*);
void* fun_wr(void*);

int main(int argc,char** argv)
{
  data = 0;
  pthread_rwlock_init(&lock,NULL);
  
  pthread_attr_t attr;
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);

  pthread_t tid;
  for(int i = 0;i < 5;i++)
  {
    pthread_create(&tid,&attr,fun_rd,NULL);
  }

  sleep(5);
  for(int i = 0;i < 5;i++)
  {
    int* p = malloc(sizeof(int));
    *p = i + 1;
    pthread_create(&tid,&attr,fun_wr,p);
    usleep(2000);
  }
  pthread_rwlock_destroy(&lock);
  pthread_exit((void*)0);
}

void* fun_rd(void* num)
{
  int ret;
  while(1)
  {
    
    ret = pthread_rwlock_tryrdlock(&lock);
    if(ret == 0)
    {
      printf("read data = %d\n",data);
      pthread_rwlock_unlock(&lock);
      sleep(1);
    }
  }
}
void* fun_wr(void* num)
{
  int ret;
  while(1)
  {
    ret = pthread_rwlock_trywrlock(&lock);
    if(ret == 0)
    {
      data = *(int*)num;
      printf("write data = %d\n",data);
      pthread_rwlock_unlock(&lock);
      sleep(1);
    }
  }
}
